<?php
/**
 * (jobs)
 */
namespace App\Jobs\ProductStockup;

use App\Models\ProductStockup\Stockup;
use App\Models\SsBasic\StockupAreaSkuEstimate;
use App\Models\SsBasic\StockupAreaSkuRatio;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class StockupAreaSkuEstimateJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $estimates;


    /**
     * AreaSkuEstimateJob constructor.
     * @param $estimates
     */
    public function __construct($estimates)
    {
        $this->estimates = $estimates;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->estimates);
    }

    private function exeFillData($estimates){

        foreach ($estimates as $estimate){
            $classifyId = $estimate->classify_id;
            if(!$classifyId) continue;

            $stockups = Stockup::query()
                ->where('area_id',$estimate->area_id)
                ->where('classify_id',$classifyId)
                ->get();
            foreach ($stockups as $stockup){
                $key = $stockup->area_id.'_'.$stockup->psku_id;
                $ratio = StockupAreaSkuRatio::getSkuRatio($key);

                //sku预估
                $areaSkuEstimate = StockupAreaSkuEstimate::query()->firstOrNew(['area_psku' => $key]);
                for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
                    $estimateNum = intval(round($estimate->{'estimate_num'.$i} * $ratio));
                    $stockup->{'estimate_num'.$i} = $estimateNum;
                    $areaSkuEstimate->{'estimate_num'.$i} = $estimateNum;
                }
                $stockup->save();
                $areaSkuEstimate->save();

            }
        }
    }

}
